package com.jamal2362.apktool.patcher;

import android.content.Context;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Patcher {
	private Context context;
	private String projectPath;
	private String patchPath;

	public Patcher(Context ctx, String project, String patch) {
		this.context = ctx;
		this.projectPath = project;
		this.patchPath = patch;
	}

	public void getRules(File patchFile) throws Exception {
        ZipFile zip = new ZipFile(patchFile);
        Enumeration e = zip.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
			if (entry.getName().equals("rules.txt")) {
				InputStream is = zip.getInputStream(entry);
				try {
					List<String> rules = parseRules(zip.getInputStream(entry));
					if (!rules.isEmpty()) {
						new Patch(context, rules);
					}
				} finally {
					is.close();
				}
				break;
			}
        }
	}

	private List<String> parseRules(InputStream input) {
		List<String> result = new ArrayList<String>();
		try {
			String line;
			BufferedReader reader = new BufferedReader(new InputStreamReader(input));
			while ((line = reader.readLine()) != null) {
				line = line.trim();
				if (!line.startsWith("#"))
					result.add(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
